<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <button id="btn">按钮</button>
  <script>
    var btn = document.getElementById("btn");

    function addEvent(ele, type, fn) {
      // ie9以上
      // 浏览器能力检测
      if (ele.addEventListener) {
        // 如果能进这个分支就说明能用addEventListener注册事件
        ele.addEventListener(type, fn);
      } else if (ele.attachEvent) {
        // 如果能注册这个分支就说明能用attachEvent注册事件
        ele.attachEvent("on" + type, fn);
      } else {
        // 进入这个分支就能用 on 注册事件
        ele["on" + type] = fn;
      }
    }

    addEvent(btn, "click", function () {
      alert("我被点击了");
    })
  </script>
</body>

</html>